package com.t.bricks.bussiness.db.dao.shoppingcart.impl;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Repository;

import com.t.bricks.bussiness.db.dao.shoppingcart.ShoppingCartDao;
import com.t.bricks.bussiness.db.entity.shoppingcart.ShoppingCart;
import com.t.bricks.bussiness.db.entity.shoppingcart.WaresSmall;
import com.t.bricks.bussiness.db.mapper.shoppingcart.ShoppingCartMapper;
import com.t.bricks.bussiness.model.shoppingcart.ConditionShoppingCart;
import com.t.bricks.model.Logger;
import com.t.bricks.model.MsgEmity;
import com.t.bricks.model.OrderInfoList;
import com.t.bricks.model.Page;
import com.t.bricks.utils.function.data.IntegerUtil;

@Repository
public class ShoppingCartDaoImpl implements ShoppingCartDao {
	
	private Logger logger = Logger.getLogger(ShoppingCartDaoImpl.class);

	@Autowired
	private ShoppingCartMapper shoppingCartMapper;

	@Value("${app.findPage.dLikeDate:配置文件中的当前库全文检索时间范围dLikeDate未设置}")
	private String sLikeDate;

	/**
	 * 添加
	 * @param shoppingCart
	 * @return MsgEmity
	 */
	@Override
	public MsgEmity add(ShoppingCart shoppingCart) {
		try {
			int i = shoppingCartMapper.add(shoppingCart);
			if (i < 1) {
				logger.error("新增未能得到预期影响值(预期1):", i);
				return new MsgEmity(false, "新增数据失败！", 7001);
			}
		} catch (Exception e) {
			logger.error("新增时发生异常:", e.getMessage());
			return new MsgEmity(false, "新增失败！", 7002);
		}
		
		return new MsgEmity(true, "新增成功！", shoppingCart);
	}

	/**
	 * 删除
	 * @param uId 记录编号
	 * @param iVersion 数据版本号
	 * @return MsgEmity
	 */
	@Override
	public MsgEmity del(String uId, Integer iVersion) {
		try {
			int i = shoppingCartMapper.del(uId, iVersion);
			if (i < 1) {
				Integer k = shoppingCartMapper.getiVersion(uId);//如果删除的影响数小于1,则检查数据是否存在
				if (null == k) {
					return new MsgEmity(true, "成功，数据已经删除！", 7999);//删除影响数失败,但数据也不存在则视为成功
				}
				
				if (!iVersion.equals(k)) {
					return new MsgEmity(false, "删除数据失败，系统中的数据可能已经被更新！", 7001);
				}

				logger.error("删除未能得到预期影响值(预期1):", i);
				return new MsgEmity(false, "删除数据失败！", 7002);
			}
		} catch (Exception e) {
			logger.error("删除时发生异常:", e.getMessage());
			return new MsgEmity(false, "删除失败！", 7003);
		}
		
		return new MsgEmity(true, "删除成功！", 7999);
	}
	
	/**
	 * 根据Id查询数据
	 * @param uId
	 * @return MsgEmity
	 */
	@Override
	public MsgEmity findById(String uId) {
		ShoppingCart shoppingCart = null;
		try {
			shoppingCart = shoppingCartMapper.findById(uId);
			if (null == shoppingCart) {
				return new MsgEmity(false, "数据不存在！", 7001);
			}
		} catch (Exception e) {
			logger.error("查询发生异常:", e.getMessage());
			return new MsgEmity(false, "查询失败！", 7002);
		}
		
		return new MsgEmity(true, "查询成功！", shoppingCart);
	}

	/**
	 * 检查待新增内容是否存在重复数据
	 * @param shoppingCartData
	 * @return MsgEmity 出现重复则返回true,若码值返回7008则表示发生异常,否则表示没有重复
	 */
	@Override
	public MsgEmity checkRepeatByAdd(ShoppingCart shoppingCartData) {
		int i = 0;
		try {
			i = shoppingCartMapper.checkRepeatByAdd(shoppingCartData);
			if (0 == i) {
				return new MsgEmity(false, "查询成功！没发现重复", 7007);
			}
		} catch (Exception e) {
			logger.error("检查待新增内容是否存在重复数据发生异常:", e.getMessage());
			return new MsgEmity(false, "查询失败，请查看异常日志", 7008);
		}
		
		return new MsgEmity(true, "查询成功！发现重复", i);//将查询到的数量(或sql中的构造码)返回以便特殊业务要求
	}
	
	/**
	 * 查询分页信息
	 * @param page 分页信息对象
	 * @param orders 排序数据集合
	 * @param sLikeStr 全文检索
	 * @param condition 查询条件对象
	 * @return MsgEmity
	 */
	@Override
	public MsgEmity findByPage(Page page, OrderInfoList orders, String sLikeStr,
			ConditionShoppingCart condition) {
		if ("配置文件中的当前库全文检索时间范围dLikeDate未设置".equals(sLikeDate)) {
			sLikeDate = "3";
		}
		
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(new Date());
		calendar.add(Calendar.DATE, - IntegerUtil.strToInt(sLikeDate, 3));//日期加m天
		Date dLikeDateSt = calendar.getTime();
		Date dLikeDateEd = new Date();
		
		int iCount = 0;
		try {
			iCount = shoppingCartMapper.findByPageCount(sLikeStr, dLikeDateSt, dLikeDateEd, condition);
		} catch (Exception e) {
			logger.error("查询数量发生异常", e.getMessage());
			return new MsgEmity(false, "查询数量失败！", 7001);
		}
		
		if (iCount < 1) {
			return new MsgEmity(true, "没有相关数据！", page);
		}

		page.setCountRow(iCount);

		List<ShoppingCart> list = null;
		try {
			list = shoppingCartMapper.findByPage(page,
					(null == orders) ? null : orders.getOrderInfoList(),
					sLikeStr, dLikeDateSt, dLikeDateEd, condition);
			if (null == list) {
				logger.error("查询数据发生异常,执行的返回值为:null,预期值不应为null");
				return new MsgEmity(false, "查询操作失败！", 7002);
			}
		} catch (Exception e) {
			logger.error("查询分页数据发生异常:", e.getMessage());
			return new MsgEmity(false, "查询请求失败，请查看异常日志！", 7003);
		}

		page.setRecordList(list);
		
		if (null != sLikeStr) {
			return MsgEmity.success(page, "查询成功！", "由于使用了全文检索,因此数据查询限制为近", sLikeDate, "天创建的数据");
		}
		
		return new MsgEmity(true, "查询成功！", page);
	}
	
	/**
	 * 根据记录编号查询符合分页数据的某条记录
	 * @param uId 记录编号
	 * @return MsgEmity
	 */
	@Override
	public MsgEmity findByPageRow(String uId) {
		ShoppingCart shoppingCart = null;
		try {
			shoppingCart = shoppingCartMapper.findByPageRow(uId);
			if (null == shoppingCart) {
				return new MsgEmity(false, "数据不存在！", 7001);
			}
		} catch (Exception e) {
			logger.error("查询发生异常:", e.getMessage());
			return new MsgEmity(false, "查询失败！", 7002);
		}
		
		return new MsgEmity(true, "查询成功！", shoppingCart);
	}
	
	/**
	 * 查询搜索用的数据
	 * 警告:本方法只允许内部使用,不能开放到外部接口
	 * @param whereStr 查询条件字符串
	 * @param orders 排序数据集合
	 * @return MsgEmity
	 */
	@Override
	public MsgEmity findBySearch(String whereStr, OrderInfoList orders) {
		if (null == whereStr || "".equals(whereStr.trim())) {
			return new MsgEmity(false, "查询条件不允许为空！", 7001);
		}

		List<ShoppingCart> list = null;
		try {
			list = shoppingCartMapper.findBySearch(whereStr.trim(),
					(null == orders) ? null : orders.getOrderInfoList());
			if (null == list) {
				logger.error("查询数据发生异常,执行的返回值为:null,预期值不应为null");
				return new MsgEmity(false, "查询操作失败！", 7002);
			}
		} catch (Exception e) {
			logger.error("查询分页数据发生异常:", e.getMessage());
			return new MsgEmity(false, "查询请求失败，请查看异常日志！", 7003);
		}
		
		return new MsgEmity(true, "查询成功！", list);
	}
	
	/**
	 * 修改状态
	 * @param uId 编号
	 * @param iState 状态值
	 * @param iVersion 记录版本号
	 * @param sMemo 备注
	 * @return MsgEmity 返回执行情况
	 */
	@Override
	public MsgEmity changeState(String uId, Integer iState, Integer iVersion, String sMemo) {
		try {
			int i = shoppingCartMapper.changeState(uId, iState, iVersion, sMemo);
			if (i < 1) {
				Integer temp = shoppingCartMapper.getiVersion(uId);//如果影响数小于1,则检查数据
				if (null == temp) {
					return new MsgEmity(false, "没有找到对应数据！", 7001);//删除影响数失败,但数据也不存在则视为成功
				}
				
				if (iVersion != temp.intValue()) {
					return new MsgEmity(false, "更新状态失败，系统中的数据可能已经被更新！", 7002);
				}

				logger.error("更新状态未能得到预期影响值(预期1):", i);
				return new MsgEmity(false, "更新状态数据失败！", 7004);
			}
		} catch (Exception e) {
			logger.error("更新状态时发生异常:", e.getMessage());
			return new MsgEmity(false, "更新状态失败！", 7005);
		}
		
		return new MsgEmity(true, "更新状态成功！", 7999);
	}

	//---------------------------- 自动生成代码结束 ----------------------------//
	
	/**
	 * 修改数量
	 * @param uId 购物车记录
	 * @param iVersion 当前版本号
	 * @param iAppendCount 增加(减少)的数量
	 * @return MsgEmity
	 */
	@Override
	public MsgEmity editCount(String uId, Integer iVersion, Integer iAppendCount) {
		try {
			int i = shoppingCartMapper.editCount(uId, iVersion, iAppendCount);
			if (i < 1) {
				Integer temp = shoppingCartMapper.getiVersion(uId);//如果影响数小于1,则检查数据
				if (null == temp) {
					return new MsgEmity(false, "没有找到对应数据！", 7001);//删除影响数失败,但数据也不存在则视为成功
				}
				
				if (iVersion != temp.intValue()) {
					return new MsgEmity(false, "更新状态失败，系统中的数据可能已经被更新！", 7002);
				}

				logger.error("更新状态未能得到预期影响值(预期1):", i);
				return new MsgEmity(false, "更新状态数据失败！", 7004);
			}
		} catch (Exception e) {
			logger.error("更新状态时发生异常:", e.getMessage());
			return new MsgEmity(false, "更新状态失败！", 7005);
		}
		
		return new MsgEmity(true, "更新状态成功！", 7999);
	}
	
	/**
	 * 检查状态
	 * @return int
	 */
	@Override
	public MsgEmity validState() {
		try {
			shoppingCartMapper.validState();
		} catch (Exception e) {
			logger.error("检查状态发生异常:", e.getMessage());
			return new MsgEmity(false, "检查状态失败！", 7005);
		}
		
		return new MsgEmity(true, "检查状态成功！", 7999);
	}
	
	/**
	 * 查询商品购物车数据
	 * @param sCustomerId 顾客账号
	 * @param sWaresId 商品编号
	 * @return ShoppingCart
	 */
	@Override
	public MsgEmity findByWaresId(String sCustomerId, String sWaresId) {
		try {
			ShoppingCart shoppingCart = shoppingCartMapper.findByWaresId(sCustomerId, sWaresId);
			return new MsgEmity(true, "正常查询成功！", shoppingCart);
		} catch (Exception e) {
			logger.error("查询商品购物车数据发生异常:", e.getMessage());
			return new MsgEmity(false, "查询商品购物车数据失败！", 7001);
		}
	}
	
	/**
	 * 查找商品信息
	 * @param sWaresId 商品编号
	 * @return
	 */
	@Override
	public MsgEmity findWares(String sWaresId) {
		try {
			WaresSmall waresSmall = shoppingCartMapper.findWares(sWaresId);
			if (null == waresSmall) {
				return MsgEmity.err(7001, "没有数据");
			}
			
			return new MsgEmity(true, "正常查询成功！", waresSmall);
		} catch (Exception e) {
			logger.error("查询商品购物车数据发生异常:", e.getMessage());
			return new MsgEmity(false, "查询商品购物车数据失败！", 7002);
		}
	}

	/**
	 * 批量删除数据
	 * @param ids 记录编号集合
	 * @return MsgEmity
	 */
	@Override
	public MsgEmity dels(List<String> ids) {
		if (ids.size() <= 40) {
			int i = dels40(ids);
			if (i != ids.size()) {
				return MsgEmity.err(i, "删除未能正确完成");
			}
			
			return MsgEmity.success(7999, "删除成功");
		}
		
		int iSum = ids.size();
		int iCount = 0;
		List<String> temp = new ArrayList<>(40);
		while(ids.size() > 0) {
			temp.clear();
			
			for (int i = ids.size() -1; i >= 0; i--) {
				temp.add(ids.get(i));
				ids.remove(i);
				if (temp.size() >= 40) {
					break;
				}
			}
			
			iCount = iCount + dels40(ids);
		}

		if (iCount != iSum) {
			return MsgEmity.err(iCount, "删除未能正确完成");
		}
		
		return MsgEmity.success(7999, "删除成功");
	}
	
	/**
	 * 批量删除
	 * @param ids
	 * @return
	 */
	private int dels40(List<String> ids) {
		try {
			return shoppingCartMapper.dels(ids);
		} catch (Exception e) {
			logger.error("批量删除数据发生异常:", e.getMessage());
			return 0;
		}
	}

}
